<template>
	<div class="map">
		<el-amap :center="center" :zoom="zoom" :style="{ width, height }" @init="init">
			<el-amap-search-box placeholder="请输入关键字" @select="searchSelect"></el-amap-search-box>
			<el-amap-control-geolocation
				ref="geolocation"
				position="RT"
				:enable-high-accuracy="true"
				:convert="true"
				:need-address="true"
				extensions="all"
				@complete="getLocation"
			></el-amap-control-geolocation>
			<el-amap-control-tool-bar></el-amap-control-tool-bar>
			<el-amap-control-scale></el-amap-control-scale>
			<el-amap-marker :position="center"> </el-amap-marker>
		</el-amap>
	</div>
</template>

<script>
export default {
	name: 'Map',
	props: {
		lng: {
			type: Number,
			default: 0,
		},
		lat: {
			type: Number,
			default: 0,
		},
		height: {
			type: String,
			default: '400px',
		},
		width: {
			type: String,
			default: '100%',
		},
		zoom: {
			type: Number,
			default: 17,
		},
		center: {
			type: Array,
			default: () => {
				return [116.407387, 39.904179];
			},
		},
	},
	methods: {
		init(o) {
			//初始化后定位到当前城市
			o.plugin('AMap.Geolocation', () => {
				// eslint-disable-next-line no-undef
				const geolocation = new AMap.Geolocation({
					timeout: 10000,
					GeoLocationFirst: true,
					maximumAge: 0,
					extensions: 'all',
					needAddress: true,
				});
				geolocation.getCurrentPosition();
				// eslint-disable-next-line no-undef
				AMap.Event.addListener(geolocation, 'complete', (data) => {
					this.getLocation(data);
				});
			});
			o.on('click', (e) => {
				this.$emit('update:center', [e.lnglat.lng, e.lnglat.lat]);
				this.$emit('click', {
					lng: e.lnglat.lng,
					lat: e.lnglat.lat,
				});
			});
		},
		searchSelect(event) {
			const { address, district, adcode } = event.poi;
			const { lat, lng } = event.poi.location;
			this.$emit('update:center', [lng, lat]);
			this.$emit('select', {
				lat,
				lng,
				name,
				address,
				district,
				adcode,
			});
		},
		getLocation(e) {
			if (e.info === 'SUCCESS') {
				this.$emit('update:center', [e.position.lng, e.position.lat]);
				this.$emit('location', {
					lng: e.position.lng,
					lat: e.position.lat,
					address: e.formattedAddress,
					addressComponent: e.addressComponent,
				});
			}
		},
	},
};
</script>
<style>
.amap-sug-result {
	z-index: 9999;
}
</style>
<style scoped lang="scss">
.map {
	position: relative;
	&-search {
		position: absolute;
	}
}
</style>
